<template>
  <div id="system-update">
    <div class="form-wrap mb20">
      <div class="form-title">{{data.title}}:</div>
			<div v-for="(item, idx) in data.fields" :key="idx">
        <os-entry :item='item' v-if="item.type=='entry'">
          {{upgrade_value[idx]}}
        </os-entry>
        <os-input :item="item" v-if="item.type=='input'&&idx!=2"
        v-model="upgrade_value[idx]" @operate="selectFile" width="300px" />
        <os-entry :item="item" v-if="idx==3">
          <el-select class="select-middle" v-model="upgrade_value[3]"
          :popper-append-to-body="false">
            <el-option v-for="(item, idx) in data.save_select"
            :key='idx' :label="item.label" :value="item.value"></el-option>
          </el-select>
        </os-entry>
      </div>
      <div class="value alone-right">
        <!-- 检查更新按钮，暂时隐藏 -->
        <!-- <div class="btn btn-blue">{{$t('btn.checkUpdate')}}</div> -->
        <div class="btn btn-blue" @click="handle_update">{{$t('btn.update')}}</div>
      </div>
		</div>
    <!-- <div class="divide-line"></div> -->
    <div class="form-wrap mb20">
      <div class="form-title">{{data.title1}}:</div>
      <os-entry :item="data.fields1[0].label">{{upgrade_value[0]}}</os-entry>
      <os-entry :item="data.fields1[1].label">{{onlineStatus}}</os-entry>
      <!-- <div class="value alone-right" v-if="onlineAvailable"> -->
      <div class="value alone-right" v-if="true">
        <div class="btn btn-blue" @click="onlineUpgrade" v-if="onlineAvailable">{{$t("btn.update")}}</div>
      </div>
    </div>
    <div class="toolbar">{{data.toolbar}}</div>
    <input type="file" ref="upload" @change="handleChange" style="width: 0; height: 0;"/>
    <os-modal :notification="notification" :loading="showModal"></os-modal>
  </div>
</template>

<script>
import { mapState } from 'vuex'

  export default {
    data(){
      return {
        upgrade_value: ['--', '', '', '0'],
        select_timer: null,
        file: null,
        install: false,
        showModal: false,
        notification: "",
        onlineAvailable: false,
        onlineStatus: "--",
      }
    },
		computed:{
			data() {
				return this.$t('system.update')
      },
      ...mapState({
        durationLong: state => state.info.durationLong,
        durationMedium: state => state.info.durationMedium,
      })
		},
    methods: {
      get_sysupgrade(){
        this.$req.get('/webapi?op=get_sys_version').then(res => {
          console.log(res)
          this.$set(this.upgrade_value, 0, res.sysversion)
        })
      },
      selectFile(){
        if(this.select_timer){
          return false
        } else {
          this.$refs.upload.click()
          this.select_timer = setTimeout(() => {
            this.select_timer = null
          }, 3000)
        }
      },
      handleChange(e){
        // method: post  multiple: multiple  enctype: multipart/form-data
        // FormData FileReader
        console.log(e.target.files)
        let file = e.target.files[0]
        this.upgrade_value.splice(1, 1, e.target.files[0].name)
        let formData = new FormData()
        formData.append('firmware', file)
        this.file = formData
        // let URL = window.URL || window.wenkitURL
        // console.log(URL.createObjectURL(e.target.files[0]))
        let reader = new FileReader()
        reader.onload = e=> {
          // console.log(e.target.result)
        }
        reader.readAsDataURL(file)
        // FormData.(get getAll keys)
        // 用同一个字段append多个值
        // console.log(formData.getAll('file'), formData.get('file'), formData.keys())
        // const config = {
        //   headers: { "Content-Type": "multipart/form-data" }
        // };
        // this.axios.post("/.../uploadTest", param, config).then(res => {
        //   console.log(res);
        // });
        // 获取 window 的 URL 工具
        // var URL = window.URL || window.webkitURL;
        // 通过 file 生成目标 url  并不是本地文件系统的路径
        // var imgURL = URL.createObjectURL(file);
        // 用这个 URL 产生一个 <img> 将其显示出来
        // $('.fbpj .container').prev().find("img").attr('src', imgURL);
        // 使用下面这句可以在内存中释放对此 url 的伺服，跑了之后那个 URL 就无效了
           //URL.revokeObjectURL(imgURL);
      },
      handle_update(){
        if(this.file == null && this.upgrade_value[1]==""){
          this.$message({
            type: "warning",
            message: this.$t("notification.lackFile"),
            showClose: true,
          })
          return
        }
        console.log(this.upgrade_value[3])
        if(this.file == null){
          // TODO  url升级
          console.log(this.upgrade_value[1])
          this.longLoading("post", "/webapi?op=url_upgrade", {
            os_url: this.upgrade_value[1],
            save_upgrade: this.upgrade_value[3],
          },
          ()=> {}, "showModal", "notification", this.$t("notification.sysupgradeLoading"),
            this.$t("notification.updateSuccess"), this.durationLong, false, {
              "1": this.$t("notification.updateSuccess"),
              "-4": this.$t("nitification.updateFailed"),
              "-6": this.$t("notification.downloadFileFailed"),
            })
          return
        }

        const loading = this.createLoading()
        console.log("loading")
        this.$req.post('/webapi?op=sysupgrade_upload_file', this.file).then(res=> {
          console.log(res)
          this.longLoading("post", "/webapi?op=sysupgrade_execute", {
          save_upgrade: this.upgrade_value[3]}, ()=> {
            this.file = null
            this.upgrade_value.splice(1, 1, "")
            // this.goLogin()
          }, "showModal", "notification", this.$t("notification.sysupgradeLoading"),
          this.$t("notification.updateSuccess"), this.durationLong, loading)
          // this.$req.post('/webapi?op=sysupgrade_execute', {
          // save_upgrade: this.upgrade_value[3]}, { timeout: Infinity }).then(async res=> {
          //   loading.close()
          //   this.install = true
          //   await new Promise((resolve, reject)=> {
          //     setTimeout(()=> {
          //       this.install = false
          //       resolve()
          //     }, this.durationLong)
          //   })
          //   this.file = null
          //   this.upgrade_value.splice(1, 1, "")
          //   this.$message({
          //     type: "success",
          //     message: this.$t("notification.updateSuccess"),
          //     showClose: true,
          //   })
          //   this.$store.dispatch("user/resetToken").then(()=> {
          //     this.$router.replace({
          //       path: "/login",
          //       query: {
          //         redirect: "/home"
          //       }
          //     })
          //   })
          // }).finally(()=> {
          //   loading.close()
          // })
        }).catch(res=> {
          if(res.code == "-4") {
            loading.close()
            this.$message({
              type: 'error',
              message: this.$t("notification.invalidFileType"),
              showClose: true,
            })
          } else if( res.code == "-6"){
            loading.close()
            this.$message({
              type: 'error',
              message: this.$t("notification.uploadFileFailed"),
              showClose: true,
            })
          }
        }).finally(()=> {
          loading? loading.close() : ""
        })
        // this.proxy_req('post', '/webapi?op=sysupgrade_upload_file', this.file, res=> {
        //   if(res.code=="1"){

        //   } else {
        //     this.$message({
        //       type: 'danger',
        //       message: 'file upload failed',
        //     })
        //   }
        // }, true)
      },
      onlineCheck(){
        this.$req.get("/webapi?op=online_upgrade_check").then(res=> {
          this.onlineAvailable = true
          this.onlineStatus = res.online_version
        }).catch(err=> {
          console.log(this.data)
          this.onlineAvailable = false
          this.onlineStatus = this.data.latest
        }).finally(()=> {

        })
      },
      onlineUpgrade(){
        // this.proxy_req("post", "/webapi?op=online_upgrade_apply", null, res=> {}, true, {
        //   "1": this.$t("notification.updateSuccess"),
        //   "-4": this.$t("nitification.updateFailed"),
        //   "-6": this.$t("notification.downloadFileFailed"),
        // } )
        this.longLoading("post", "/webapi?op=online_upgrade_apply", null,
          ()=> {}, "showModal", "notification", this.$t("notification.onlineUpgradeLoading"),
            this.$t("notification.updateSuccess"), this.durationLong, false, {
              "1": this.$t("notification.updateSuccess"),
              "-4": this.$t("nitification.updateFailed"),
              "-6": this.$t("notification.downloadFileFailed"),
            })
      }
    },
    created(){
      this.$bus.emit('changeTab', 0)
      this.get_sysupgrade()
      this.onlineCheck()
    }
  }
</script>

<style lang="scss" scoped>
  .select-mini {
  	/deep/ .el-input{
  		.el-input__inner{
  			width: 90px;
  			padding-left: 10px;
  			padding-right: 10px;
  			height: 25px;
  		}
  		.el-input__icon{
  			line-height: 25px;
  		}
  	}
  }
  .select-middle {
    /deep/ .el-input {
      .el-input__inner {
        width: 300px;
      }
    }
  }
  .divide-line{
    height: 20px;
    border-bottom: 1px solid #cccccc;
    margin-bottom: 15px;
  }
</style>
